<template>
  <view class="medicine-recognition">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">药品识别与查询</text>
      <text class="page-subtitle">拍照识别或搜索药品信息</text>
    </view>

    <!-- 搜索区 -->
    <view class="search-section">
      <view class="search-bar">
        <input 
          v-model="searchQuery"
          type="text"
          placeholder="输入药品名称搜索..."
          class="search-input"
          @confirm="handleSearch"
          confirm-type="search"
          :disabled="isAnalyzing"
        />
        <view class="search-btn" @tap="handleSearch">
          <view v-if="isAnalyzing && !selectedImage" class="btn-spinner"></view>
          <text v-else class="search-icon">🔍</text>
        </view>
      </view>

      <!-- Show searching text below search bar when searching by text -->
      <view v-if="isAnalyzing && !selectedImage" class="searching-state">
        <view class="spinner"></view>
        <text class="searching-text">正在搜索药品信息...</text>
      </view>

      <!-- 拍照 / 相册 -->
      <view v-if="!selectedImage && !isAnalyzing" class="camera-section">
        <view class="camera-icon">📷</view>
        <text class="camera-text">拍照或相册选择识别药品</text>
        <view class="camera-btn" @tap="chooseImage">
          <text class="camera-btn-text">识别药品</text>
        </view>
      </view>

      <!-- 图片预览 -->
      <view v-if="selectedImage" class="image-preview">
        <image 
          :src="selectedImage" 
          class="preview-image" 
          mode="aspectFill" 
          @tap="previewImage" 
        />

        <!-- Updated analyzing text to match design -->
        <view v-if="isAnalyzing" class="analyzing">
          <view class="spinner"></view>
          <text class="analyzing-text">正在识别药品...</text>
        </view>
        <view v-if="!isAnalyzing" class="reset-btn" @tap="resetAnalysis">
          <text class="reset-text">重新拍照</text>
        </view>
      </view>
    </view>

    <!-- AI识别结果 -->
    <view v-if="medicineInfo" class="medicine-info">
      <view class="info-header">
        <text class="info-title">💊 药品信息</text>
      </view>

      <view class="info-content">
        <!-- 分段渲染，遇到加粗标记使用style -->
        <view v-for="(line, index) in formattedLines" :key="index" style="margin-bottom:6rpx;">
          <text v-for="(part, i) in line.parts" :key="i" :style="part.bold ? 'font-weight:bold;color:#409eff;' : ''">
            {{ part.text }}
          </text>
        </view>
      </view>
    </view>

    <!-- 常用药 -->
    <view v-if="!medicineInfo && !isAnalyzing" class="common-medicines">
      <text class="common-title">常用药品</text>
      <view class="medicines-grid">
        <view 
          v-for="medicine in commonMedicines" 
          :key="medicine.name"
          class="medicine-item"
          @tap="selectMedicine(medicine.name)"
        >
          <text class="medicine-emoji">{{ medicine.emoji }}</text>
          <view class="medicine-text">
            <text class="medicine-item-name">{{ medicine.name }}</text>
            <text class="medicine-category">{{ medicine.category }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 免责声明 -->
    <view v-if="!medicineInfo && !isAnalyzing" class="disclaimer-card">
      <view class="disclaimer-content">
        <text class="warning-icon">⚠️</text>
        <view class="disclaimer-text">
          <text class="disclaimer-title">重要提醒</text>
          <text class="disclaimer-desc">药品识别结果仅供参考，不能替代专业医疗建议。用药前请咨询医生或药师，严格按照医嘱或说明书使用。</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'

const searchQuery = ref('')
const selectedImage = ref(null)
const medicineInfo = ref(null)
const aiRawText = ref('') // 保存AI原始文本
const isAnalyzing = ref(false)
const commonMedicines = ref([
  { name: '阿司匹林', category: '解热镇痛药', emoji: '💊' },
  { name: '布洛芬', category: '非甾体抗炎药', emoji: '💊' },
  // 添加更多常用药品
])

/** 调用 AI 接口 */
const callAI = (prompt, imageBase64 = null) => {
  isAnalyzing.value = true

  const requestData = {
    model: 'openai/gpt-4.1',
    max_tokens: 512, // 限制内容长度
    messages: [
      {
        role: 'user',
        content: [
          { type: 'text', text: prompt }
        ]
      }
    ]
  }

  if (imageBase64) {
    requestData.messages[0].content.push({
      type: 'image_url',
      image_url: { url: `data:image/jpeg;base64,${imageBase64}` }
    })
  }

  wx.request({
    url: 'https://openrouter.ai/api/v1/chat/completions',
    method: 'POST',
    header: {
      'Authorization': 'Bearer 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', // 替换成你的 API Key
      'Content-Type': 'application/json'
    },
    data: requestData,
    success: (res) => {
      const aiText = res.data?.choices?.[0]?.message?.content || ''
      console.log('🧠 AI 返回原始内容:', aiText)
      aiRawText.value = aiText
      medicineInfo.value = true
    },
    fail: (err) => {
      console.error('AI识别失败:', err)
      wx.showToast({ title: '识别失败', icon: 'error' })
    },
    complete: () => {
      isAnalyzing.value = false
    }
  })
}

/** 选择图片 */
const chooseImage = () => {
  wx.chooseMedia({
    count: 1,
    mediaType: ['image'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      selectedImage.value = res.tempFiles[0].tempFilePath

      const fs = wx.getFileSystemManager()
      fs.readFile({
        filePath: selectedImage.value,
        encoding: 'base64',
        success: (res) => callAI(
          '识别这张图片里面是否有药品盒子或说明书，如有直接返回药品信息和用法用量，不超过250字',
          res.data
        ),
        fail: () => wx.showToast({ title: '图片读取失败', icon: 'error' })
      })
    }
  })
}

/** 点击图片放大预览 */
const previewImage = () => {
  if (!selectedImage.value) return
  wx.previewImage({
    urls: [selectedImage.value],
    current: selectedImage.value
  })
}

/** 搜索药品 */
const handleSearch = () => {
  if (!searchQuery.value.trim()) return
  callAI(`请提供药品 "${searchQuery.value}" 的信息、用法用量、不良反应，内容不超过250字`)
}

/** 重置 */
const resetAnalysis = () => {
  selectedImage.value = null
  medicineInfo.value = null
  aiRawText.value = ''
}

/** 选择常用药品 */
const selectMedicine = (name) => {
  searchQuery.value = name
  handleSearch()
}

/** 格式化AI文本：加粗 & 列表 */
const formattedLines = computed(() => {
  if (!aiRawText.value) return []

  const lines = aiRawText.value.split('\n')
  return lines.map(line => {
    const parts = []

    // 匹配 **加粗**
    const regex = /\*\*(.+?)\*\*/g
    let lastIndex = 0
    let match
    while ((match = regex.exec(line)) !== null) {
      if (match.index > lastIndex) {
        parts.push({ text: line.slice(lastIndex, match.index), bold: false })
      }
      parts.push({ text: match[1], bold: true })
      lastIndex = match.index + match[0].length
    }
    if (lastIndex < line.length) {
      parts.push({ text: line.slice(lastIndex), bold: false })
    }

    // 列表符号替换 - → •
    parts.forEach(p => {
      if (!p.bold) {
        p.text = p.text.replace(/^\s*[-–—]\s+/gm, '• ')
      }
    })

    return { parts }
  })
})
</script>


<style scoped>
.medicine-recognition {
  min-height: 100vh;
  background: linear-gradient(to bottom, #f0fdf4, #dbeafe);
  padding: 32rpx;
  padding-bottom: 160rpx;
}

.page-header {
  margin-bottom: 48rpx;
}

.page-title {
  font-size: 40rpx;
  font-weight: 600;
  color: #1f2937;
  display: block;
  margin-bottom: 8rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
}

.search-section {
  background: white;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 48rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.search-bar {
  display: flex;
  gap: 16rpx;
  margin-bottom: 32rpx;
}

.search-input {
  flex: 1;
  padding: 0 24rpx;
  height: 88rpx;
  line-height: 88rpx;
  border: 1px solid #d1d5db;
  border-radius: 16rpx;
  font-size: 28rpx;
  background: #f9fafb;
  box-sizing: border-box;
}

.search-btn {
  padding: 0 28rpx;
  height: 88rpx;
  background: #8b5cf6;
  border-radius: 16rpx;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-btn:active {
  background: #7c3aed;
}

.search-icon {
  color: white;
  font-size: 28rpx;
}

/* Added searching state styles */
.searching-state {
  text-align: center;
  padding: 24rpx 32rpx 0;
}

.spinner {
  width: 64rpx;
  height: 64rpx;
  border: 4rpx solid #e5e7eb;
  border-top: 4rpx solid #8b5cf6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 24rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.searching-text {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
}

.camera-section {
  text-align: center;
  padding-top: 16rpx;
}

.camera-icon {
  font-size: 64rpx;
  margin-bottom: 16rpx;
}

.camera-text {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
  margin-bottom: 24rpx;
}

.camera-btn {
  background: #8b5cf6;
  color: white;
  padding: 24rpx 48rpx;
  border-radius: 16rpx;
  display: inline-block;
  transition: all 0.2s;
}

.camera-btn:active {
  background: #7c3aed;
}

.camera-btn-text {
  font-size: 28rpx;
  color: white;
}

.image-preview {
  text-align: center;
}

.preview-image {
  width: 100%;
  height: 384rpx;
  border-radius: 16rpx;
  margin-bottom: 32rpx;
}

.analyzing {
  margin: 32rpx 0;
  text-align: center;
}

.analyzing-text {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
  margin-top: 24rpx;
}

.reset-btn {
  background: white;
  border: 1px solid #d1d5db;
  padding: 16rpx 32rpx;
  border-radius: 16rpx;
  display: inline-block;
  transition: all 0.2s;
}

.reset-btn:active {
  background: #f9fafb;
}

.reset-text {
  font-size: 28rpx;
  color: #374151;
}

.medicine-info {
  background: white;
  border-radius: 24rpx;
  padding: 48rpx;
  margin-bottom: 48rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.info-header {
  margin-bottom: 32rpx;
}

.info-title {
  font-weight: 600;
  color: #1f2937;
  font-size: 32rpx;
  display: block;
}

.info-content {
  font-size: 28rpx;
  line-height: 1.8;
  color: #374151;
}

/* Added button spinner for search loading state */
.btn-spinner {
  width: 32rpx;
  height: 32rpx;
  border: 3rpx solid rgba(255, 255, 255, 0.3);
  border-top: 3rpx solid white;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

/* Added common medicines styles */
.common-medicines {
  margin-bottom: 48rpx;
}

.common-title {
  font-weight: 600;
  color: #1f2937;
  display: block;
  margin-bottom: 24rpx;
  font-size: 32rpx;
}

.medicines-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
}

.medicine-item {
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  transition: all 0.2s;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.medicine-item:active {
  transform: scale(0.98);
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.15);
}

.medicine-emoji {
  font-size: 48rpx;
}

.medicine-text {
  display: flex;
  flex-direction: column;
}

.medicine-item-name {
  font-weight: 500;
  color: #1f2937;
  font-size: 28rpx;
  display: block;
  margin-bottom: 4rpx;
}

.medicine-category {
  font-size: 24rpx;
  color: #6b7280;
  display: block;
}

/* Added disclaimer card styles */
.disclaimer-card {
  background: #fffbeb;
  border: 1px solid #fbbf24;
  border-radius: 24rpx;
  padding: 32rpx;
}

.disclaimer-content {
  display: flex;
  align-items: flex-start;
  gap: 24rpx;
}

.warning-icon {
  font-size: 40rpx;
  flex-shrink: 0;
  margin-top: 4rpx;
}

.disclaimer-text {
  flex: 1;
}

.disclaimer-title {
  font-weight: 500;
  color: #92400e;
  display: block;
  margin-bottom: 8rpx;
  font-size: 28rpx;
}

.disclaimer-desc {
  font-size: 28rpx;
  color: #b45309;
  line-height: 1.6;
  display: block;
}
</style>
